import { ElLoading } from 'element-plus';
/**
 * 判断是否有http域名
 */
export const getFileUrl = (url) => {
    const isHasHttp = new RegExp('http').test(url)
    return isHasHttp ? url : '域名' + url
}
//图片压缩
export const compressUpload = (file, isShowLoading = true) => {
    let _loading = {}
    return new Promise((resolve) => {
        if(isShowLoading){
            _loading = ElLoading.service({
                text: '压缩中',
                background: 'rgba(0, 0, 0, 0.7)'
            })
        }
        const reader = new FileReader();
        const image = new Image();
        image.onload = () => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const width = image.width * 0.5; //宽缩一半
            const height = image.height * 0.5;//高缩一半
            canvas.width = width;
            canvas.height = height;
            context.clearRect(0, 0, width, height);
            context.drawImage(image, 0, 0, width, height);
            const dataUrl = canvas.toDataURL(file.type);
            const blobData = dataURItoBlob(dataUrl, file.type);
            _loading.close();
            console.log(blobData.size / 1024 / 1024); //压缩后大小
            resolve(blobData);
        };
        reader.onload = (e) => {
            image.src = e.target.result;
        };
        reader.readAsDataURL(file);
    })
}
//图片格式转换——base64转Blob对象
export const dataURItoBlob = (dataURI, type) => {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: type });
}